package com.example.service.shiro.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bean.shiro.SysPermissionEntity;
import com.example.bean.shiro.SysUserEntity;
import com.example.dao.shiro.SysPermissionMapper;
import com.example.dao.shiro.SysRoleMapper;
import com.example.dao.shiro.SysUserMapper;
import com.example.service.shiro.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 李宇航
 * @since 2020-06-02
 */
@Service
public class SysUserImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserImpl.class);

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    SysPermissionMapper sysPermissionMapper;

    @Override
    public Set<String> getUserRolesSet(String username) {

        List<String> roleList =  sysUserMapper.getRoleByUserName(username);
        return new HashSet(roleList);
    }

    @Override
    public List<String> getUserPermissionsSet(String username) {
        List<SysPermissionEntity> permissionList = sysPermissionMapper.queryByUser(username);
        List<String> permissionSet = new ArrayList<>(permissionList.size());
        for (SysPermissionEntity po : permissionList) {
            if(StringUtils.isNotBlank(po.getPerms())){
                permissionSet.add(po.getPerms());
            }
        }
        log.info("-------通过数据库读取用户拥有的权限Perms------username： "+ username+",Perms size: "+ (permissionSet==null?0:permissionSet.size()) );
        return permissionSet;
    }

    @Override
    public SysUserEntity getUserByName(String userName) {
        return sysUserMapper.selectOne( new QueryWrapper<SysUserEntity>().lambda().eq(SysUserEntity::getUsername, userName));
    }
}
